using MediatR;
using Traceability.API.APPLications.Commands.ImmunityInfo;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.ImmunityInfo
{
    /// <summary>
    /// 删除免疫信息命令处理器
    /// </summary>
    public class DeleteImmunityInfoCommandHandler : IRequestHandler<DeleteImmunityInfoCommand, APIResult<bool>>
    {
        private readonly MyDbContext _context;

        public DeleteImmunityInfoCommandHandler(MyDbContext context)
        {
            _context = context;
        }

        public async Task<APIResult<bool>> Handle(DeleteImmunityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();
            
            try
            {
                var immunityInfo = await _context.ImmunityInfos.FindAsync(request.ID);
                if (immunityInfo == null)
                {
                    result.Code = APIEnum.删除失败;
                    result.Message = "免疫信息不存在";
                    return result;
                }

                _context.ImmunityInfos.Remove(immunityInfo);
                await _context.SaveChangesAsync(cancellationToken);

                result.Data = true;
                result.Code = APIEnum.删除成功;
                result.Message = "免疫信息删除成功";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.删除失败;
                result.Message = $"删除免疫信息失败: {ex.Message}";
            }
            
            return result;
        }
    }
} 